package com.yin.jia.liang.controller;

import com.yin.jia.liang.entity.TeachPl;
import com.yin.jia.liang.entity.User;
import com.yin.jia.liang.service.TeachPlService;
import com.yin.jia.liang.service.TeachService;
import com.yin.jia.liang.vo.TeachPlVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("pl/teach")
public class TeachPlController {

    @Autowired
    TeachPlService teachPlService;
    @Autowired
    TeachService teachService;

    @RequestMapping(value = "{teachId}", method = RequestMethod.GET)
    public String list(HttpSession session, Model model, @PathVariable Integer teachId) {
        List<TeachPlVo> vo = teachPlService.findByTeachId(teachId);
        model.addAttribute("pl", vo);
        return "pl/teach/list";
    }

    @RequestMapping(value = "", method = RequestMethod.GET)
    public String list(HttpSession session, Model model) {

        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }
        List<TeachPlVo> vo = teachPlService.findByUserId(user.getId());

        model.addAttribute("pl", vo);
        return "pl/teach/list";
    }

    @RequestMapping(value = "add", method = RequestMethod.POST)
    public String index(@ModelAttribute TeachPl teachPl, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }
        teachPl.setUserId(user.getId());
        teachPlService.save(teachPl);
        return "redirect:/teach/show/"+teachPl.getTeachId();
    }

    @RequestMapping(value = "del/{id}", method = RequestMethod.GET)
    public String del(@PathVariable Integer id, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }
        if ("admin".equals(user.getUsername())) {
            teachPlService.delete(id);
        }
        return "redirect:/pl/teach/list";
    }
}
